from django.core import paginator
from django.http import JsonResponse, HttpResponseRedirect
from django.shortcuts import redirect, render
from lib.handler import dispatcherBase
from django.core.paginator import Paginator
from common.models import Customer
from django.db.models import Q


def listcustomers(request):
    qs = Customer.objects.values()
    pagesize = request.params['pagesize']
    pagenum = request.params['pagenum']
    keywords = request.params.get('keywords')
    if keywords:
        keywords_list = keywords.split()
        query = Q()
        for k in keywords_list:
            query |= Q(name__contains=k)
        qs = qs.filter(query)
    pgnt = Paginator(qs, pagesize)
    page = pgnt.get_page(pagenum)
    retlist = list(page)
    return JsonResponse({'ret': 0, 'retlist': retlist})

def addcustomers(request):
    info = request.params['data']
    record = Customer.objects.create(
        name = info['name'],
        phonenumber = info['phonenumber'],
        address = info['address']
    )
    return JsonResponse({'ret': 0, 'id': record.id})

def modifycustomers(request):
    customerid = request.params['id']
    newdata = request.params['newdata']
    try:
        customer = Customer.objects.get(id=customerid)
    except Customer.DoesNotExist:
        return JsonResponse({'ret': 1, 'msg': f"id为'{customerid}'的客户不存在"})
    if 'name' in newdata:
        customer.name = newdata['name']
    if 'phonenumber' in newdata:
        customer.phonenumber = newdata['phonenumber']
    if 'address' in newdata:
        customer.address = newdata['address']
    customer.save()
    return JsonResponse({'ret': 0})

def deletecustomers(request):
    customerid = request.params['id']
    try:
        customer = Customer.objects.get(id=customerid)
    except Customer.DoesNotExist:
        return {
            'ret': 1,
            'msg': f"id为'{customerid}'的客户不存在"
        }
    customer.delete()
    return JsonResponse({'ret': 0})


action_handler_dict = {
    'list_customer': listcustomers,
    'add_customer': addcustomers,
    'modify_customer': modifycustomers,
    'del_customer': deletecustomers,
}

def dispatcher(request):
    return dispatcherBase(request, action_handler_dict)
